package hu.debrecen.adastra.card.service;

import hu.debrecen.adastra.card.repository.PlayerStatisticsRepository;
import hu.debrecen.adastra.card.repository.domain.Account;
import hu.debrecen.adastra.card.repository.domain.PlayerStatistics;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;

public class PlayerStatisticsService {

	private static final Logger LOGGER = LoggerFactory.getLogger(PlayerStatisticsService.class);

	private final PlayerStatisticsRepository playerStatisticsRepository;

	@Inject
	public PlayerStatisticsService(final PlayerStatisticsRepository playerStatisticsRepository) {
		this.playerStatisticsRepository = playerStatisticsRepository;
	}

	public PlayerStatisticsEvent start(final Account account) {
		return new PlayerStatisticsEvent(this.playerStatisticsRepository, account);
	}

	public static class PlayerStatisticsEvent {

		private final PlayerStatisticsRepository playerStatisticsRepository;

		private Account account;

		private PlayerStatistics playerStatistics;

		public PlayerStatisticsEvent(final PlayerStatisticsRepository playerStatisticsRepository, final Account account) {
			Preconditions.checkNotNull(playerStatisticsRepository);
			Preconditions.checkNotNull(account);

			this.playerStatisticsRepository = playerStatisticsRepository;

			this.playerStatistics = this.playerStatisticsRepository.findPlayerStatisticsByAccount(account.getUsername());
		}

		public PlayerStatisticsEvent increaseJoinGameCount() {
			this.playerStatistics.setJoinGameCount(this.getPlayerStatistics().getJoinGameCount() + 1);
			return this;
		}

		public PlayerStatisticsEvent increaseCreateGameCount() {
			this.playerStatistics.setCreateGameCount(this.getPlayerStatistics().getCreateGameCount() + 1);
			return this;
		}

		public PlayerStatisticsEvent increaseFinishedGameCount() {
			this.playerStatistics.setFinishedGameCount(this.getPlayerStatistics().getFinishedGameCount() + 1);
			return this;
		}

		public PlayerStatisticsEvent increaseCallCount() {
			this.playerStatistics.setCallCount(this.getPlayerStatistics().getCallCount() + 1);
			return this;
		}

		public void save() {
			if (this.playerStatistics != null) {
				this.playerStatisticsRepository.save(this.playerStatistics);
			}
		}

		private PlayerStatistics getPlayerStatistics() {
			if (this.playerStatistics == null) {
				PlayerStatisticsService.LOGGER.debug("find playerStatistics by username({})", this.account.getUsername());
				this.playerStatistics = this.playerStatisticsRepository.findPlayerStatisticsByAccount(this.account.getUsername());
			}
			return this.playerStatistics;
		}

	}

}
